// 应用程序JavaScript

// 测试模型可用性
async function testModel(modelType, modelName) {
    if (!modelName) {
        showAlert('warning', '模型名称不能为空');
        return;
    }

    try {
        showLoading();
        let response;
        let requestBody;
        
        if (modelType === 'llm') {
            // 测试 LLM 模型
            requestBody = {
                model: modelName,
                messages: [
                    {
                        role: "user",
                        content: "hellow"
                    }
                ],
                max_tokens: 50
            };
            
            response = await fetch('/v1/chat/completions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer test-token'
                },
                body: JSON.stringify(requestBody)
            });
            
        } else if (modelType === 'embedding') {
            // 测试 Embedding 模型
            requestBody = {
                model: modelName,
                input: "hellow"
            };
            
            response = await fetch('/v1/embeddings', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer test-token'
                },
                body: JSON.stringify(requestBody)
            });
            
        } else if (modelType === 'reranker') {
            // 测试 Reranker 模型
            requestBody = {
                model: modelName,
                query: "hellow",
                documents: [
                    "hellow"
                ]
            };
            
            response = await fetch('/v1/rerank', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer test-token'
                },
                body: JSON.stringify(requestBody)
            });
            
        } else {
            showAlert('warning', '不支持的模型类型: ' + modelType);
            return;
        }

        if (response.ok) {
            const result = await response.json();
            showAlert('success', `模型 ${modelName} 测试成功！响应正常。`);
            console.log('测试响应:', result);
        } else {
            const error = await response.json();
            showAlert('danger', `模型 ${modelName} 测试失败: ${error.error?.message || '未知错误'}`);
            console.error('测试失败:', error);
        }
        
    } catch (error) {
        console.error('测试模型失败:', error);
        showAlert('danger', `测试模型 ${modelName} 时发生网络错误: ${error.message}`);
    } finally {
        hideLoading();
    }
}

// 切换模型配置状态
async function toggleStatus(id) {
    if (!confirm('确定要切换此配置的启用状态吗？')) {
        return;
    }

    try {
        showLoading();
        const response = await fetch(`/model-config/${id}/toggle`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        });

        const result = await response.json();
        
        if (response.ok && result.code === 200) {
            showAlert('success', result.message);
            // 延迟刷新页面
            setTimeout(() => {
                window.location.reload();
            }, 1000);
        } else {
            showAlert('danger', result.message || '操作失败');
        }
    } catch (error) {
        console.error('切换状态失败:', error);
        showAlert('danger', '网络错误，请重试');
    } finally {
        hideLoading();
    }
}

// 删除模型配置
async function deleteConfig(id) {
    if (!confirm('确定要删除此配置吗？此操作不可恢复！')) {
        return;
    }

    try {
        showLoading();
        const response = await fetch(`/model-config/${id}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            }
        });

        const result = await response.json();
        
        if (response.ok && result.code === 200) {
            showAlert('success', '删除成功');
            // 延迟刷新页面
            setTimeout(() => {
                window.location.reload();
            }, 1000);
        } else {
            showAlert('danger', result.message || '删除失败');
        }
    } catch (error) {
        console.error('删除失败:', error);
        showAlert('danger', '网络错误，请重试');
    } finally {
        hideLoading();
    }
}

// 显示提示消息
function showAlert(type, message) {
    // 移除现有的alert
    const existingAlert = document.querySelector('.alert-dynamic');
    if (existingAlert) {
        existingAlert.remove();
    }

    // 创建新的alert
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show alert-dynamic`;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    // 设置绝对定位样式
    alertDiv.style.position = 'fixed';
    alertDiv.style.top = '20px';
    alertDiv.style.right = '20px';
    alertDiv.style.zIndex = '9999';
    alertDiv.style.maxWidth = '400px';
    alertDiv.style.minWidth = '300px';

    // 插入到body
    document.body.appendChild(alertDiv);

    // 自动消失
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

// 显示加载状态
function showLoading() {
    document.body.classList.add('loading');
    
    // 创建加载遮罩
    const overlay = document.createElement('div');
    overlay.id = 'loading-overlay';
    overlay.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999;
    `;
    overlay.innerHTML = `
        <div class="text-center text-white">
            <div class="spinner-border mb-2" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <div>处理中...</div>
        </div>
    `;
    
    document.body.appendChild(overlay);
}

// 隐藏加载状态
function hideLoading() {
    document.body.classList.remove('loading');
    const overlay = document.getElementById('loading-overlay');
    if (overlay) {
        overlay.remove();
    }
}

// 表单验证
function validateForm(form) {
    const inputs = form.querySelectorAll('input[required], select[required], textarea[required]');
    let isValid = true;

    inputs.forEach(input => {
        if (!input.value.trim()) {
            input.classList.add('is-invalid');
            isValid = false;
        } else {
            input.classList.remove('is-invalid');
            input.classList.add('is-valid');
        }
    });

    // 验证JSON格式的请求头
    const requestHeaders = form.querySelector('#request_headers');
    if (requestHeaders && requestHeaders.value.trim()) {
        try {
            JSON.parse(requestHeaders.value);
            requestHeaders.classList.remove('is-invalid');
            requestHeaders.classList.add('is-valid');
        } catch (e) {
            requestHeaders.classList.add('is-invalid');
            showAlert('warning', '请求头必须是有效的JSON格式');
            isValid = false;
        }
    }

    return isValid;
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 表单提交验证
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            if (!validateForm(form)) {
                e.preventDefault();
                return false;
            }
        });
    });

    // 输入框实时验证
    const inputs = document.querySelectorAll('input, select, textarea');
    inputs.forEach(input => {
        input.addEventListener('blur', function() {
            if (this.hasAttribute('required')) {
                if (!this.value.trim()) {
                    this.classList.add('is-invalid');
                    this.classList.remove('is-valid');
                } else {
                    this.classList.remove('is-invalid');
                    this.classList.add('is-valid');
                }
            }
        });
    });

    // JSON格式验证
    const requestHeaders = document.querySelector('#request_headers');
    if (requestHeaders) {
        requestHeaders.addEventListener('blur', function() {
            if (this.value.trim()) {
                try {
                    JSON.parse(this.value);
                    this.classList.remove('is-invalid');
                    this.classList.add('is-valid');
                } catch (e) {
                    this.classList.add('is-invalid');
                    this.classList.remove('is-valid');
                }
            }
        });
    }

    // 图片预览
    const vendorImgInput = document.querySelector('#vendor_img');
    if (vendorImgInput) {
        vendorImgInput.addEventListener('input', function() {
            const url = this.value.trim();
            if (url) {
                // 创建预览图片
                let preview = document.querySelector('#img-preview');
                if (!preview) {
                    preview = document.createElement('img');
                    preview.id = 'img-preview';
                    preview.style.cssText = 'max-width: 100px; max-height: 50px; margin-top: 10px; border: 1px solid #ddd; border-radius: 4px;';
                    this.parentNode.appendChild(preview);
                }
                preview.src = url;
                preview.onerror = function() {
                    this.style.display = 'none';
                };
                preview.onload = function() {
                    this.style.display = 'block';
                };
            } else {
                const preview = document.querySelector('#img-preview');
                if (preview) {
                    preview.remove();
                }
            }
        });
    }

    // 自动关闭alert
    setTimeout(() => {
        const alerts = document.querySelectorAll('.alert:not(.alert-dynamic)');
        alerts.forEach(alert => {
            const bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        });
    }, 3000);
});
